<template>
  <el-button class="mb-4" type="success" @click="showForm = true">
    新增数据同步配置
  </el-button>
  <!-- 弹出表单 -->
  <el-dialog
    v-model="showForm"
    :close-on-click-modal="false"
    :title="!formData.id ? '新增' : '修改'"
    width="70%"
  >
    <el-form
      ref="formRef"
      :model="formData"
      label-width="auto"
      @keyup.enter="addHandle"
    >
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template #title>
            <div class="custom-title">
              基础信息
            </div>
          </template>
          <el-row :gutter="20" :span="24">
            <el-col :span="12">
              <el-form-item :rules="[{required : true,message: '同步任务名称不能为空'}]" label="名称:" prop="name"  >
                <el-input v-model="formData.name" placeholder="请输入同步任务名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[{required : true,message: '数据同步类型为必选项'}]" label="类型:" prop="type">
                <el-select v-model="formData.type" placeholder="请选择数据同步类型">
                  <el-option
                    v-for="item in dsTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" :span="24">
            <el-col :span="12">
              <el-form-item :rules="[{required : true,message: '来源数据源为必选项'}]" label="来源数据源"  prop="fromId">
                <el-select v-model="formData.fromId" clearable placeholder="请选择来源数据源">
                  <el-option
                    v-for="item in dsOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :rules="[{required : true,message: '目标数据源为必选项'}]" label="目标数据源"  prop="toId">
                <el-select v-model="formData.toId" clearable placeholder="请选择目标数据源" >
                  <el-option
                    v-for="item in dsOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template #title>
            <div class="custom-title">
              字段映射
            </div>
          </template>
          <el-row :gutter="20" :span="24">
            <el-col :span="8">
              <el-form-item :rules="[{required : true,message: '来源表表名不能为空'}]" label="来源表" prop="fromTableName">
                <el-input v-model="formData.fromTableName" placeholder="请输入来源表名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :rules="[{required : true,message: '目标表表名不能为空'}]" label="目标表" prop="toTableName">
                <el-input v-model="formData.toTableName" placeholder="请输入目标表名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button :loading=loadingTag type="primary" @click="getTableFieldsList(Number(formData.fromId),Number(formData.toId),formData.fromTableName,formData.toTableName)">加载表字段</el-button>
            </el-col>
            <el-col :span="4">
              <el-button type="success" @click="addFieldMapping">添加映射关系</el-button>
            </el-col>
          </el-row>
          <el-table :data="formData.fieldsMappingArr" border>
            <el-table-column align="center" label="字段映射">
              <el-table-column align="center" label="来源字段" prop="fromFieldName">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.fromFieldName"
                    placeholder="请选择来源字段"
                    @change="(val) => updateFieldInfo(scope.row, val, 'from')">
                    <el-option
                      v-for="item in fromFieldsOptions"
                      :key="item.fieldName"
                      :label="item.fieldName"
                      :value="item.fieldName"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="来源字段类型" prop="fromFieldType">
                <template #default="scope">
                  {{ getFieldInfo(scope.row.fromFieldName, fromFieldsOptions)?.fieldType }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="来源字段描述" prop="fromFieldAnnotation">
                <template #default="scope">
                  {{ getFieldInfo(scope.row.fromFieldName, fromFieldsOptions)?.fieldAnnotation }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="目标字段" prop="toFieldName">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.toFieldName"
                    placeholder="请选择目标字段"
                    @change="(val) => updateFieldInfo(scope.row, val, 'to')">
                    <el-option
                      v-for="item in toFieldsOptions"
                      :key="item.fieldName"
                      :label="item.fieldName"
                      :value="item.fieldName"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="目标字段类型" prop="toFieldType">
                <template #default="scope">
                  {{ getFieldInfo(scope.row.toFieldName, toFieldsOptions)?.fieldType }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="目标字段描述" prop="toFieldAnnotation">
                <template #default="scope">
                  {{ getFieldInfo(scope.row.toFieldName, toFieldsOptions)?.fieldAnnotation }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" prop="operation">
                <template #default="scope">
                  <el-button link type="danger" @click="removeField(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <!-- 表单底部操作按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showForm = false">取消</el-button>
        <el-button type="primary" @click="addHandle">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus/es"
//弹窗开关绑定
const showForm = ref(false)
let loadingTag = ref(false)
import { ref, defineExpose, defineEmits, reactive, watch } from "vue"
import { submitData, getOne, getDataSourcesList } from "@/api/sync/dataSync"
import { getFields } from "@/api/pub/dataSource"
//数据刷新
const emit = defineEmits(["refreshDataList"])
//折叠面板展开
const activeNames = ref(['1','2'])
//表单数据模型
const formData = reactive({
  id: "",
  name: "",
  type: "",
  fromId: "",
  toId: "",
  fromTableName: "",
  toTableName: "",
  fieldsMappingArr: [
    {
      fromFieldName: "",
      fromFieldType: "",
      fromFieldAnnotation: "",
      toFieldName: "",
      toFieldType: "",
      toFieldAnnotation: ""
    }
  ],
})
const formRef = ref()
//初始化数据
const init = (id?: number) => {
  showForm.value = true
  
  if (id) {
    // 编辑模式：查询单条数据
    getOneData(id)
  } else {
    // 新增模式：清空数据
    // 重置表单数据
    if (formRef.value) {
      formRef.value.resetFields()
    }
    formData.id = ""
    formData.name = ""
    formData.type = ""
    formData.fromId = ""
    formData.toId = ""
    formData.fromTableName = ""
    formData.toTableName = ""
    formData.fieldsMappingArr = [] // 清空映射数组
  }
}

//查询单条数据
const getOneData = (id: number) => {
  getOne(id).then((res) => {
    Object.assign(formData, res.data)
    // 如果返回的数据中没有 fieldsMappingArr，则初始化为空数组
    if (!formData.fieldsMappingArr) {
      formData.fieldsMappingArr = []
    }
    
    // 如果有表名和数据源ID，自动加载表字段信息
    if (formData.fromId && formData.toId && formData.fromTableName && formData.toTableName) {
      loadingTag.value = true
      getTableFieldsList(Number(formData.fromId), Number(formData.toId), formData.fromTableName, formData.toTableName)
    }
  })
}


// 表单提交
const addHandle = () => {
  submitData(formData)
    .then(() => {
      ElMessage.success({
        message: "操作成功",
        duration: 500,
        onClose: () => {
          showForm.value = false
          if (formRef.value) {
            formRef.value.resetFields() // 重置表单数据
          }
          emit("refreshDataList")
        },
      })
    })
    .catch((error) => {
      console.error("添加数据失败", error)
      ElMessage.error("操作失败，请检查网络或数据是否正确")
    })
}
//新增与编辑弹窗关闭时清空form表单
watch(showForm, (newVal) => {
  if (!newVal) {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    // 确保关闭弹窗时也清空字段映射数组
    formData.id = ""
    formData.name = ""
    formData.type = ""
    formData.fromId = ""
    formData.toId = ""
    formData.fromTableName = ""
    formData.toTableName = ""
    formData.fieldsMappingArr = [] // 完全清空映射数组
  }
})

const dsTypeOptions = [
  {
    value: "1",
    label: "批量同步",
  },
  {
    value: "2",
    label: "实时同步",
  },
]
const dsOptions = ref()
const getDataSourceList = () => {
  getDataSourcesList().then((res) => {
    dsOptions.value = res.data
  })
}

const fromFieldsOptions = ref()
const toFieldsOptions = ref()
const getTableFieldsList = (fromId:number,toId:number,fromTableName : string,toTableName:string) => {
  loadingTag.value = true
  getFields(fromId,fromTableName).then((res) => {
    if (Array.isArray(res.data) && res.data.length > 0) {
      fromFieldsOptions.value = res.data
    }else {
      ElMessage.error("未获取到来源表表字段")
    }
  })
  getFields(toId,toTableName).then((res) => {
    if (Array.isArray(res.data) && res.data.length > 0) {
      toFieldsOptions.value = res.data
    }else {
      ElMessage.error("未获取到目标表表字段")
    }
  }).finally(() => {
    loadingTag.value = false
  })
}

const getFieldInfo = (field: string, options: any[]) => {
  console.log("fieldInfo:"+field)
  return options.find(option => option.fieldName === field);
}
// 更新字段信息的方法
const updateFieldInfo = (row: any, fieldName: string, type: 'from' | 'to') => {
  const options = type === 'from' ? fromFieldsOptions.value : toFieldsOptions.value;
  const fieldInfo = options.find(option => option.fieldName === fieldName);
  
  if (fieldInfo) {
    if (type === 'from') {
      row.fromFieldType = fieldInfo.fieldType;
      row.fromFieldAnnotation = fieldInfo.fieldAnnotation;
    } else {
      row.toFieldType = fieldInfo.fieldType;
      row.toFieldAnnotation = fieldInfo.fieldAnnotation;
    }
  }
}
const addFieldMapping = () => {
  formData.fieldsMappingArr.push({
    fromFieldName: "",
    fromFieldType: "",
    fromFieldAnnotation: "",
    toFieldName: "",
    toFieldType: "",
    toFieldAnnotation: "",
  });
}

const removeField = (index: number) => {
  formData.fieldsMappingArr.splice(index, 1);
}

getDataSourceList()

//加载
defineExpose({
  init,
})
</script>

<style scoped>
.custom-title {
  font-size: 18px;
}
</style>
